<?php
/**绑定认证页面
 * Class ValidateController
 * @package Home\Controller
 * @author leiying
 */

namespace Home\Controller;
use Think\Controller;

class ValidateController extends Controller {
    private static $time_limit = 60;//单位：s

    /**验证手机号
     * @param $phone
     * @return bool
     * @author leiying
     */
    protected function check_phone($phone){
        if(preg_match("/^1[34578]{1}\d{9}$/",$phone)){
            return true;
        }else{
            return false;
        }
    }


    /**检查验证记录在数据库中是否已经存在
     * @param $key
     * @return bool
     * @author leiying
     */
    protected function check_code ($phone,$type='')
    {
        $count = M("validate_record")->where(array("record_key"=>$phone,"record_type"=>$type))->count();
        if($count > 0){
            return true;
        }else{
            return false;
        }
    }

    /**移除过期的验证记录
     * @return mixed
     * @author leiying
     */
    protected function remove_expired_code ()
    {
        $current_time = time();
        $res = M("validate_record")->where(array('expired_time'=>array('lt',$current_time)))->delete();
        return $res;
    }

    /**从数据库中获取验证记录信息，会将ext_info数组解析与结果合并
     * @param $phone
     * @return array|bool
     * @author leiying
     */
    protected function get_validate_record ($phone)
    {
        /*移除过期的验证记录*/
        $this->remove_expired_code();

        $res = M("validate_record")->where(array('record_key'=>$phone))->find();
        if($res){
            $res["ext_info"] = unserialize($res['ext_info']);
            $record = array(
                "record_key" => $res['record_key'],// 验证代码
                "record_code" => $res['record_code'],// 验证代码
                "record_type" => $res['record_type'],// 业务类型
                "last_send_time" => $res['last_send_time'],// 开始时间
                "expired_time" => $res['expired_time'],// 过期时间
                "create_time" => $res['create_time']// 创建时间
            );

            $record = array_merge($record, $res['ext_info']);
            return $record;
        }else{
            return false;
        }
    }


    /**保存一个验证记录到数据库，如果存在则更新
     * @param $key  验证标识(手机号)
     * @param $code 验证值(验证码)
     * @param $type 验证类型
     * @param $last_send_time
     * @param $expired_time 过期时间
     * @param array $ext_info   扩展信息
     * @author leiying
     */
    protected function save_code($key, $code, $type, $last_send_time, $expired_time, $ext_info = array())
    {
        $record = array(
            "record_code" => $code,// 验证代码
            "record_type" => $type,// 业务类型
            "last_send_time" => $last_send_time,// 业务类型
            "expired_time" => $expired_time,// 过期时间
            "ext_info" => serialize($ext_info)// 扩展信息
        );

        $exist = $this->check_code($key,$type);

        if(! $exist){
            $record['record_key'] = $key;
            // 记录创建时间
            $record["create_time"] = time();
            /* insert */
            $res = M("validate_record")->add($record);
        }else{
            /* update */
            $res = M("validate_record")->where(array("record_key"=>$key,"record_type"=>$type))->save($record);
        }
        if($res === false){
            $this->error("异常错误，如有疑问请联系客服");
        }
    }

    /**发送短信验证码
     * @author leiying
     */
    public function sendCode(){

        $mobile_phone = I("post.phone",'');
        $type = I("post.type",'');

        if(!in_array($type,array("send_apply","query_progress"))){
            $this->error("异常错误，如有疑问请联系客服");
        }
        /*验证手机号*/
        if(empty($mobile_phone) || empty($type)){
            $this->error("请输入手机号码");
        }else{
            if(!$this->check_phone($mobile_phone)){
                $this->error("手机号码有误，请重填");
            }
        }

        /*查询该手机号是否有验证记录*/
        if($this->check_code($mobile_phone,$type)){
            // 获取数据库中的验证记录
            $record = $this->get_validate_record($mobile_phone);
            if($record){
                /*检查验证码条件*/
                $last_send_time	 = $record['last_send_time'];
                $create_time	 = $record['create_time'];
                $count			 = $record['count'];

                $max_sms_count = 10;// 每天每个手机号最多发送的验证码数量
                $max_sms_count_time = 60 * 60 * 24;// 发送最多验证码数量的限制时间，默认为24小时

                if((time() - $last_send_time) < self::$time_limit){//"每60秒内只能发送一次短信验证码，请稍候重试";
                    $this->error("一分钟只能发送一次，请稍候重试");
                }else if(time() - $create_time < $max_sms_count_time && $record['count'] > $max_sms_count){//24小时内最多发送10次
                    $this->error("发送验证码过于频繁，请稍后重试！");//"您发送验证码太过于频繁，请稍后重试！";
                }else{
                    $count ++;
                }
            }

        }
        /*发送验证码*/
        vendor('ypsms','','.class.php');
        $ypsms = new \ypsms();
        $res_data = $ypsms->send($mobile_phone);
        if($res_data['code'] == 100){
            if(! isset($count)){
                $ext_info = array("count" => 1);
            }else{
                $ext_info = array("count" => $count);
            }
            // 保存验证信息
            $mobile_code = $res_data['data'];//验证码
            $this->save_code($mobile_phone, $mobile_code, $type, time(), time() + 15 * 60, $ext_info);

            $this->success("短信验证码已发送");
        }else{
            $this->error("短信验证码发送失败");
        }
    }
}
